package cn.xenosp.server.module.scheduler.logs;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 项目名： service-web
 * 包路径： cn.xenosp.server.module.scheduler.logs
 * 作者：   TongHui
 * 创建时间: 2025-11-20 16:42
 * 描述: 日志捕获器
 * 版本: 1.0
 */
@Slf4j
@Component
public class ConsoleLogCapture {

    private final ConcurrentHashMap<String, ConsoleLogBuffer> logBuffers = new ConcurrentHashMap<>();
    private final int MAX_LOG_SIZE = 100 * 1024; // 100KB 最大日志大小



    /**
     * 开始捕获控制台日志
     */
    public synchronized void startCapture(String logId) {
        try {
            ConsoleLogBuffer buffer = new ConsoleLogBuffer(MAX_LOG_SIZE);
            logBuffers.put(logId, buffer);
            log.info("=== 开始捕获任务日志: " + logId + " ===");
        } catch (Exception e) {
            log.error("启动日志捕获失败: " + e.getMessage());
        }
    }

    /**
     * 停止捕获并获取日志内容
     */
    public synchronized String stopCapture(String logId) {
        try {
            ConsoleLogBuffer buffer = logBuffers.remove(logId);
            log.info("=== 停止捕获任务日志: " + logId + " ===");
            return buffer != null ? buffer.getLogContent() : "";
        } catch (Exception e) {
            log.error("停止日志捕获失败: " + e.getMessage());
            return "";
        }
    }
    public void writeToBuffer(String logId,String message) {
        log.info("=== 写入任务日志:{}  {}  ===",logId,message);
        ConsoleLogBuffer buffer = logBuffers.get(logId);
        if (buffer != null) {
            buffer.append("["+ DateUtil.date() +"]: "+message);
        }
    }
    public void EndwriteToBuffer(String logId,String message){
        log.info("=== 写入任务日志:{}  {}  ===",logId,message);
        ConsoleLogBuffer buffer = logBuffers.get(logId);
        if (buffer != null) {
            buffer.end("["+ DateUtil.date() +"]: "+message);
        }
    }
    /**
     * 获取当前捕获的日志内容
     */
    public String getLogContent(String logId) {
        ConsoleLogBuffer buffer = logBuffers.get(logId);
        return buffer != null ? buffer.getLogContent() : "";
    }

    /**
     * 清理过期的日志缓冲区
     */
    public void cleanupExpiredBuffers() {
        // 可以定期清理长时间未使用的缓冲区
        // 这里简单实现，实际项目中可以根据需要添加更复杂的清理逻辑
        if (logBuffers.size() > 50) { // 如果缓冲区超过50个，清理一半
            int targetSize = logBuffers.size() / 2;
            logBuffers.entrySet().stream()
                    .limit(logBuffers.size() - targetSize)
                    .forEach(entry -> logBuffers.remove(entry.getKey()));
        }
    }

    /**
     * 自定义日志缓冲区
     */
    private static class ConsoleLogBuffer {
        private final StringBuilder logContent = new StringBuilder();
        private final int maxSize;

        public ConsoleLogBuffer(int maxSize) {
            this.maxSize = maxSize;
        }

        public void append(String message) {
            // 如果超过最大大小，移除前面的内容
            if (logContent.length() + message.length() > maxSize) {
                int overflow = (logContent.length() + message.length()) - maxSize;
                logContent.delete(0, overflow);
            }
            logContent.append(message).append("\n\t");
        }
        public void end(String message) {
            logContent.append("\n");
            logContent.append(message);
        }

        public String getLogContent() {
            return logContent.toString();
        }

        public int getSize() {
            return logContent.length();
        }
    }
}
